<template>
  <div class="container" style="text-align:center;" >
    <div>
      <canvas id="canvas" width="100%" height="100%"></canvas>
    </div>

    
    <el-card shadow="always" class="login-module" v-if="smdl">
        

        <form class="card login-container " style="position:absolute;width:372px;background-color:rgba(255, 255, 255, 0.17);top:40%;left:50%;margin: -150px 0 0 -200px;">

        <div slot="header" class="clearfix formTitlt" style="margin-top: 10px;margin-left: 63%;color: white">
          <span>扫码登录</span>
          <span class="titIconbox">
          <!-- <i class="iconfont xu-saomadenglu2 fa-lg iconcolor"></i> -->
          <i class="iconfont xu-saomadenglu01 el-icon--right fa-lg pointer" @click="getLoginQ(smdl = !smdl)"></i>
        </span>
        </div>
        <div class="title mt-5" style="text-align:center;color:rgba(245, 247, 250, 0.88);font-size:24px;margin-top: 70px">自动化测试平台</div>

        
        <div style="margin-left: 4%;">
        <el-input
        placeholder="请输入用户名"
        v-model="username"
        prop="username"
        autocomplete="on"
        clearable style="text-align:center;width:250px;height:32px;margin-top:30px;">
        </el-input>
        <el-input
        type="password"
        placeholder="请输入密码"
        v-model="password"
        clearable style="text-align:center;width:250px;height:32px;margin-top:30px;">
        </el-input>
        <br>
        <div style="margin-top:30px;">

        <div class="divinput">
        <el-input
        type="text"
        placeholder="请输入验证码"
        style="width:155px;height:30px;"
        v-model="capMsg"
        clearable >
        </el-input> 
        </div>
        <div class="div2">
        <img :src="capPath" alt="" @click="getcapImg" style="height: 24px;min-width: 80px;" />
        </div>
        </div>
        <br>
        <el-button plain v-loading="loading" @click="CheckCaptcha()" style="size:10px;width:219px;margin-top:70px;padding: " type="primary" >登录</el-button>
        </div>
        <div style="font-size:12px;color:#ffffff;text-align:center;margin-top:30px;margin-bottom:50px">
        接口自动化、APP自动化、测试报告、任务设置
        </div>
        </form>
    </el-card>

    <el-card shadow="always" class="login-module" v-else>
        

        <form class="card login-container " style="position:absolute;width:372px;background-color:rgba(255, 255, 255, 0.17);top:40%;left:50%;margin: -150px 0 0 -200px;min-height: 533px">
            <div slot="header" class="clearfix formTitlt" style="margin-top: 10px;margin-left: 63%;color:white">
            <span >密码登录</span>
            <span class="titIconbox">
            <i class="iconfont xu-saomadenglu2 fa-lg iconcolor"></i>
            <!-- <i class="iconfont xu-saomadenglu01 el-icon--right fa-lg pointer" @click="smdl = !smdl"></i> -->
            <i class="iconfont xu-saomadenglu01 el-icon--right fa-lg pointer" @click="getLoginQ(smdl = !smdl)"></i>

            </span>
            </div>
        <div class="title mt-5" style="text-align:center;color:rgba(245, 247, 250, 0.88);font-size:24px;margin-top: 70px">自动化测试平台</div>

        
        <div style="margin-left: 4%;">
        </div>
        <div class="ewmbox" style="margin-top: 20px;">
            <div class="ewm">
                <div v-if="qrErr">
                    <img :src="qrimg" class="dim">
                    <div class="box1">
                        <span @click="getLoginQ(false)" ><font size = "5">已失效，点击重新</font></span>
                    </div>
                </div>
                <div v-else>
                    <img :src="qrimg" >
                </div>
                
            </div>


            <div class="ewmicon" style="margin-top: 10px;">
                <i class="iconfont xu-saomadenglu fa-2x iconcolor"></i>
                <p style="color:white;margin-top: 10px;">打开 微信 扫一扫登录</p>
            </div>
            <!-- <p class="smalltxt">
                <router-link class="a" to="#">免费注册</router-link>
            </p> -->
        </div>
        <div class="bottomText">
        接口自动化、APP自动化、测试报告、任务设置
        </div>
    </form>
    </el-card>
  </div>
</template>

<script>
import { requestLogin,capGet,capCheck,logQr,ChecklogQr,UserInfo,getrouter } from '../../api/api';
import { v4 as uuidv4 } from 'uuid';
import md5 from 'js-md5';
// import "@/js/slideBlock.js";
import '@/utils/vconsole.min.js'
// var vConsole = new VConsole();
export default {
  name: 'Login',
  data () {
    const validateUsername = (rule, value, callback) => {
        if (value.trim().length<1) {
          callback(new Error('用户名不能为空'))
        } else {
          callback()
        }
      };
      const validatePass = (rule, value, callback) => {
        if (value.trim().length < 1) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      };
    return {
      msg: 'login',
      loading :false,
      code: 1,
      qrimg:"http://192.168.248.168:8080/erweima/login.png?1614929994695",
      smdl: true,
      logining: false,
      show:false,
      qrErr:false,
      bsimg:"",
      username:"",
      capId:"",
      capPath:"",
      response:false,
      capMsg:"",
      password: "",
      checked: true
    }
  },
  mounted:function () {
    this.run();
    this.getcapImg();
  },
  created() {
    let that = this;
    document.onkeypress = function(e) {
      var keycode = document.all ? event.keyCode : e.which;
      if (keycode == 13 ) {
        // that.login();// 登录方法名
        // console.log(that.$router);
      }
    };
  },
  methods: {
    getRouter(token){
      let par = {"token":token}
      getrouter(par).then( _data => {
        let { msg, code, data } = _data;
        console.log("getRouter data",data);
        // this.$store.dispatch("addRoutes", res.router);
        if (data != null) {
          sessionStorage.setItem('roles', data);
        }

        // this.$store.dispatch("addRoutes",data);
        
      })

    },
    CheckLogin(uuid){
        var that = this;
        let par = {"uuid":uuid}
        that.qrErr = false
        ChecklogQr(par).then(res => {
            let {code,msg,data} = res;
            // console.log(code,msg,data);
            if (data.status) {
                console.log("登录成功",data);
                let par = {"userId":data.userId}
                UserInfo(par).then( _data => {
                    let { msg, code, data } = _data;
                    if (code == 200) {
                        sessionStorage.setItem('nickname', JSON.stringify(data.user.Nickname));
                        sessionStorage.setItem('userId', JSON.stringify(data.user.id));
                        sessionStorage.setItem('username', JSON.stringify(data.user.username));
                        sessionStorage.setItem('token', JSON.stringify(data.token));
                        if (data.user.userimg ==='') {
                            sessionStorage.setItem('usrimg', JSON.stringify('static/usr/1.jpg'));
                        } else {
                            sessionStorage.setItem('usrimg', JSON.stringify(data.user.Uimages));
                        }
                        console.log(this.$store);
                        
                        // this.getRouter(data.token)
                    }
                }).catch()
            }else if (data.NotFound){
                that.$message.error("已失效")
                console.log("已失效");
                that.qrErr = true
            }else if (data.timeout){
                that.qrErr = true
                that.$message.error("已超时，重新获取")
                console.log("已超时，重新获取");
            }else {
                that.timer = setTimeout(()=>{   //设置延迟执行

                },3000);
                clearTimeout(that.timer);
                return that.CheckLogin(uuid)
            }
        }).catch()
    },
    getLoginQ(item){
        if (!item){
            var uuid = uuidv4();
            var now = new Date().getTime();
            let par = {"uuid":uuid,"channel":"web","timestamp":now};
            console.log(par);
            logQr(par).then( res => {
                let {code,msg,data} = res;
                this.qrimg = data;
                console.log(code,msg,data);

                this.CheckLogin(uuid)
            }).catch()
        }
            
    },
    getcapImg(){
      var that = this;
      capGet().then(
        res => {
          let {code, msg, data} = res;
          that.capId = data.id;
          that.capPath = data.path;
      }).catch(
        function(error){
          that.$message.error(error)
        })
    },
    CheckCaptcha(){
      var that = this;
      let par = {"id":that.capId,"value":that.capMsg}
      if (this.username === '' || this.password === '' || this.capMsg === "") {
        this.$message({
          showClose: true,
          message: '账号或密码不能为空',
          type: 'error'
        })
        // that.loading = false
        return false
      }
      capCheck(par).then(
        res => {
          let {code,msg,data} = res;
          if (code == 200){
            this.login();
          }else{
            that.$message({
                showClose: true,
                message: '验证码输入错误',
                type: 'error'
            })
            that.getcapImg();
          }
        }
        ).catch(
        function(error) {
          that.$message.error(error)
        }
      )
    },
    getCaptcha() {
        jigsaw.init({
            el: this.$refs.captcha,
            onSuccess: this.onSuccess,
            onFail: this.onFail,
            onRefresh: this.cleanMsg
        });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    login() {
      let that = this
      that.loading = true;
      if (this.username === '' || this.password === '' || this.capMsg === "") {
        this.$message({
          showClose: true,
          message: '账号或密码不能为空',
          type: 'error'
        })
        that.loading = false
        return false
      }else {
        var par = {"username":this.username,"password":md5(this.password),"logtype": 1 ,"version": 1.01,"channel":"web"}
        requestLogin(par).then(
          _data => {
            let { msg, code, data } = _data;
            if (code == 200) {
              sessionStorage.clear();
              sessionStorage.setItem('nickname', JSON.stringify(data.user.Nickname));
              sessionStorage.setItem('userId', JSON.stringify(data.user.id));
              sessionStorage.setItem('username', JSON.stringify(data.user.username));
              sessionStorage.setItem('token', JSON.stringify(data.token));
              sessionStorage.setItem('expires', JSON.stringify(data.expires));
              if (data.user.Group != undefined) {
                if(data.user.Group.length > 0) {
                sessionStorage.setItem('role', data.user.Group[0].name);
                sessionStorage.setItem('permission', data.user.Group[0].Describe);
                }else{
                  sessionStorage.setItem('role', "ordinary");
                }
              }else{
                sessionStorage.setItem('role', "ordinary");
              }
              
              
              if (data.user.userimg ==='') {
                sessionStorage.setItem('usrimg', JSON.stringify('static/usr/1.jpg'));
              } else {
                sessionStorage.setItem('usrimg', JSON.stringify(data.user.Uimages));
              }
              that.loading = false
              // this.getRouter(data.token)
              that.$store.dispatch('setToken', data.token).then(() => {
                if (that.$route.query.redirect != undefined ){
                  that.$router.push({path: that.$route.query.redirect})
                }else{
                  that.$router.push({path: "/" })
                }
                
                that.$message("登录成功")
              })

            } else {
              that.loading = false
              that.$message({
                showClose: true,
                message: msg,
                type: 'error'
                })
              that.getcapImg();
            }
        }).catch(
            (err) => {
              that.loading = false
              console.log(err);
              that.$message.error("登录接口异常:\n"+err);
              that.response = {};
              that.res_show = false;
              that.getcapImg();
            }
        )
      }
    },
    one:function () {
        var $ = {};

        $.Particle = function( opt ) {
          this.radius = 7;
          this.x = opt.x;
          this.y = opt.y;
          this.angle = opt.angle;
          this.speed = opt.speed;
          this.accel = opt.accel;
          this.decay = 0.01;
          this.life = 1;
        };

        $.Particle.prototype.step = function( i ) {
          this.speed += this.accel;
          this.x += Math.cos( this.angle ) * this.speed;
          this.y += Math.sin( this.angle ) * this.speed;
          this.angle += $.PI / 64;
          this.accel *= 1.01;
          this.life -= this.decay;

          if( this.life <= 0 ) {
            $.particles.splice( i, 1 );
          }
        };

      $.Particle.prototype.draw = function( i ) {
        $.ctx.fillStyle = $.ctx.strokeStyle = 'hsla(' + ( $.tick + ( this.life * 120 ) ) + ', 100%, 60%, ' + this.life + ')';
        $.ctx.beginPath();
        if( $.particles[ i - 1 ] ) {
          $.ctx.moveTo( this.x, this.y );
          $.ctx.lineTo( $.particles[ i - 1 ].x, $.particles[ i - 1 ].y );
        }
        $.ctx.stroke();

        $.ctx.beginPath();
        $.ctx.arc( this.x, this.y, Math.max( 0.001, this.life * this.radius ), 0, $.TWO_PI );
        $.ctx.fill();

        var size = Math.random() * 1.25;
        $.ctx.fillRect( ~~( this.x + ( ( Math.random() - 0.5 ) * 35 ) * this.life ), ~~( this.y + ( ( Math.random() - 0.5 ) * 35 ) * this.life ), size, size );
      }

      $.step = function() {
        $.particles.push( new $.Particle({
          x: $.width / 2 + Math.cos( $.tick / 20 ) * $.min / 2,
          y: $.height / 2 + Math.sin( $.tick / 20 ) * $.min / 2,
          angle: $.globalRotation + $.globalAngle,
          speed: 0,
          accel: 0.01
        }));

        $.particles.forEach( function( elem, index ) {
          elem.step( index );
        });

        $.globalRotation += $.PI / 6;
        $.globalAngle += $.PI / 6;
      };

      $.draw = function() {
        $.ctx.clearRect( 0, 0, $.width, $.height );

        $.particles.forEach( function( elem, index ) {
          elem.draw( index );
        });
      };

    $.init = function() {
      $.canvas = document.createElement( 'canvas' );
      $.ctx = $.canvas.getContext( '2d' );
      $.width = 300;
      $.height = 300;
      $.canvas.width = $.width * window.devicePixelRatio;
      $.canvas.height = $.height * window.devicePixelRatio;
      $.canvas.style.width = $.width + 'px';
      $.canvas.style.height = $.height + 'px';
      $.ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
      $.min = $.width * 0.5;
      $.particles = [];
      $.globalAngle = 0;
      $.globalRotation = 0;
      $.tick = 0;
      $.PI = Math.PI;
      $.TWO_PI = $.PI * 2;
      $.ctx.globalCompositeOperation = 'lighter';
      document.body.appendChild( $.canvas );
      $.loop();
        };

      $.loop = function() {
        requestAnimationFrame( $.loop );
        $.step();
        $.draw();
        $.tick++;
      };
      $.init();
   },
   run: function () {
        const PHI = (1 + Math.sqrt(5)) / 2, // 1.618033988749895
        maxGeneration = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) ? 5 : 6,
        frameDuration = 1000 / 60,
        duration = 3000,
        rotationSpeed = 0.3,
        totalIterations = Math.floor(duration / frameDuration),
        maxBaseSize = 100,
        baseSizeSpeed = 0.02;

        var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d"),
        canvasWidth = document.documentElement.clientWidth,
        canvasHeight = document.documentElement.clientHeight,
        shapes = [],
        sizeVariation,
        iteration = 0,
        animationDirection = 1,
        sizeVariationRange = .15,
        baseRotation = 0,
        baseSize = 50,
        c1 = 43,
        c1S = 1,
        c2 = 205,
        c2S = 1,
        c3 = 255,
        c3S = 1;

        canvas.setAttribute("width", canvasWidth);
        canvas.setAttribute("height", canvasHeight);
        function Shape(gen, x, y, size, rotation) {
          this.generation = gen;
          this.size = size;
          this.rotation = -rotation;
          this.start = {
            x: x,
            y: y
          };
          this.end = {
            x_1: this.start.x + Math.cos(degToRad(this.rotation)) * this.size,
            y_1: this.start.y + Math.sin(degToRad(this.rotation)) * this.size,
            x_2: this.start.x + Math.cos(degToRad(this.rotation + 360 / 3)) * this.size,
            y_2: this.start.y + Math.sin(degToRad(this.rotation + 360 / 3)) * this.size,
            x_3:
              this.start.x +
              Math.cos(degToRad(this.rotation + 360 / 3 * 2)) * this.size,
            y_3:
              this.start.y + Math.sin(degToRad(this.rotation + 360 / 3 * 2)) * this.size
          };
          this.init();
        }
        Shape.prototype.init = function() {
            if (this.generation < maxGeneration) {
              var gen = this.generation + 1,
                newSize = this.size * sizeVariation,
                newRotation = this.rotation;

              shapes.push(
                new Shape(gen, this.end.x_1, this.end.y_1, newSize, newRotation)
              );
              shapes.push(
                new Shape(gen, this.end.x_2, this.end.y_2, newSize, newRotation)
              );
              shapes.push(
                new Shape(gen, this.end.x_3, this.end.y_3, newSize, newRotation)
              );
            }
            this.draw();
          };

          Shape.prototype.draw = function() {
            ctx.beginPath();
            ctx.moveTo(this.start.x, this.start.y);
      ctx.lineTo(this.end.x_1, this.end.y_1);
      ctx.moveTo(this.start.x, this.start.y);
      ctx.lineTo(this.end.x_2, this.end.y_2);
      ctx.moveTo(this.start.x, this.start.y);
      ctx.lineTo(this.end.x_3, this.end.y_3);
      //ctx.closePath();
      ctx.strokeStyle =
        "rgba(" + c1 + "," + c2 + "," + c3 + "," + 1 / this.generation / 5 + ")";
      ctx.stroke();
      //ctx.fill();
    };

    function animate() {
      //ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      ctx.globalCompositeOperation = "source-over";
      ctx.fillStyle = "rgba(0,0,0,.1)";
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);
      ctx.globalCompositeOperation = "lighter";
      shapes = [];
      shapes.push(
        new Shape(0, canvasWidth / 2, canvasHeight / 2, baseSize, baseRotation)
      );

      changeColor();
      iteration++;
      if (baseSize < maxBaseSize) baseSize += baseSizeSpeed;
      baseRotation += rotationSpeed;
      sizeVariation = easeInOutSine(
        iteration,
        1 - sizeVariationRange * animationDirection,
        sizeVariationRange * 2 * animationDirection,
        totalIterations
      );
      if (iteration >= totalIterations) {
        iteration = 0;
        animationDirection *= -1;
      }
      requestAnimationFrame(animate);
    }

    function degToRad(deg) {
      return Math.PI / 180 * deg;
    }

    function easeInOutSine(
      currentIteration,
      startValue,
      changeInValue,
      totalIterations
    ) {
      return (
        changeInValue /
          2 *
          (1 - Math.cos(Math.PI * currentIteration / totalIterations)) +
        startValue
      );
    }

    function changeColor() {
      if (c1 == 0 || c1 == 255) c1S *= -1;
      if (c2 == 0 || c2 == 255) c2S *= -1;
      if (c3 == 0 || c3 == 255) c3S *= -1;
      c1 += 1 * c1S;
      c2 += 1 * c2S;
      c3 += 1 * c3S;
    }

    ctx.globalCompositeOperation = "lighter";
    animate();

    window.addEventListener("resize", function() {
      canvasWidth = document.documentElement.clientWidth;
      canvasHeight = document.documentElement.clientHeight;

      canvas.setAttribute("width", canvasWidth);
      canvas.setAttribute("height", canvasHeight);
      ctx.strokeStyle = "rgba(66,134,240,.3)";
      ctx.globalCompositeOperation = "lighter";
    });
      },
  }

}
</script>

<style lang="scss" scoped type="text/css">
@import url("../../assets/sass/base.scss");
.dim{
    background: white;
    opacity:0.2; filter: alpha(opacity=80);
}
 
.dimback{
  background: #000;
}


body {

  overflow: hidden;
}
.box1{ position:absolute; width:calculateSize(400px); height:calculateSize(200px); left:calculateSize(90px); top:calculateSize(210px);color:white;} 
#login {
    width: 100%;
    height: 100%;
    background-color: #2d3a4b;
    .loginConbox{
      background: #2d3a4b;
    }
    .header {
        height: calculateSize(60px);
        position: relative;
        background: #2d3a4b;
        /*border-bottom: 1px solid rgba(255, 255, 255, 0.3);*/
        .logo{
            margin-left: calculateSize(30px);
            width: calculateSize(500px);
            float: left;
            height: calculateSize(40px);
            padding-top: calculateSize(10px);
            img{
            height: 100%;
            }
        }
    }

    .loginBox {
        .iconcolor {
            color: #409EFF;
        }
        padding: 74px 0 118px;
        .loginCon {
            width: calculateSize(990px);
            margin: auto;
            position: relative;
            height: calculateSize(388px);

            .el-card__header {
                border-bottom: 0px;
            }
            .title{
                font-size: 36px;
                font-weight: 600;
                color: #ffffff;
                width: calculateSize(500px);
                float: left;
                margin-top: 0px;
                &:first-child{
                    font-size: 34px;
                    margin-top: calculateSize(50px);
                    margin-bottom: calculateSize(30px);
                }
            }
            .login-module {
                width: calculateSize(380px);
                height: calculateSize(325px);
                /*margin-top: calculateSize(60px);
*/                margin-bottom: 10%;
                border: none;
                position: absolute;
                right: 0;

                .formTitlt {
                    font-size: 18px;
                    font-weight: 400;

                    .titIconbox {
                        float: right;

                        .pointer {
                            cursor: pointer;
                        }
                    }
                }
            }

            .smalltxt {
                text-align: right;
                margin-top:10px;
                .a {
                    text-decoration: none;
                    color: #999999;
                    font-size: 12px;
                    margin-left: 8px;
                }
            }
        }
    }
}





.usr_input{
  text-align:center;
  width:calculateSize(250px);
  height:calculateSize(30px);
  margin-top:calculateSize(80px);
}
canvas {
  bottom: 0;
  left: 0;
  margin: auto;
  position: absolute;
  right: 10%;
  top: 0;
}


.container {
  /*width: calculateSize(310px);*/
  width: auto;
  margin: calculateSize(100px) auto;
}
input {
  display: block;
  width: 290px;
  line-height: 40px;
  margin: 0px 0;
  padding: 0 0px;
  outline: none;
  border: 0px solid #c8cccf;
  border-radius: 4px;
  color: #6a6f77;
}
#msg {
  width: 100%;
  line-height: 40px;
  font-size: 14px;
  text-align: center;
}
a:link,
a:visited,
a:hover,
a:active {
  margin-left: calculateSize(100px);
  color: #0366d6;
}

.divinput{
  width:calculateSize(155px);
  height:calculateSize(30px);
  background-color:#0C0;
  display:inline-block;
  overflow: hidden;
}
.div2{
  
  /*width:50%;*/
  /*height:100%;*/
  background-color:white;
  display:inline-block;
  overflow: hidden;
}
.bottomText {
  font-size:12px;
  color:#ffffff;
  text-align:center;
  margin-top:calculateSize(115px);
  margin-bottom:calculateSize(50px);
}
</style>
